package com.mvprxjavartrofit.db;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.support.annotation.Nullable;

import static com.mvprxjavartrofit.entity.Const.AUTHORITIES;
import static com.mvprxjavartrofit.entity.Const.TABLE_USER;

/**
 * Created by Administrator
 * At 2016/10/20/16:26/2016
 * Project test
 */
public class UserContentProvider extends ContentProvider {
    private DbBaseHelpler db;

    private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    static{
        matcher.addURI(AUTHORITIES, TABLE_USER, 1);
    }

    @Override
    public boolean onCreate() {
        db = new DbBaseHelpler(getContext());
        if(db == null){
            return false;
        }
        return true;
    }

    @Nullable
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase database = db.getReadableDatabase();

        return database.query(TABLE_USER, projection, selection, selectionArgs, null, null, sortOrder);
    }

    @Nullable
    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Nullable
    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase database = db.getWritableDatabase();
        long rowId;

        if(matcher.match(uri) == 1){
             rowId = database.insert(TABLE_USER, "id", values);
        }
        return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase database = db.getWritableDatabase();

        if(matcher.match(uri) == 1){
            return database.delete(TABLE_USER, selection, selectionArgs);
        }

        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase database = db.getWritableDatabase();

        if(matcher.match(uri) == 1){
            return database.update(TABLE_USER, values, selection, selectionArgs);
        }

        return 0;
    }
}
